package com.laopan.elasticsearch.handler;

import com.google.gson.JsonArray;
import com.laopan.elasticsearch.bean.UpdateFieldArray;
import com.laopan.elasticsearch.bean.UpdateFieldInfo;
import com.laopan.elasticsearch.core.operation.DocOperation;
import com.laopan.elasticsearch.utils.JsonUtils;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.update.UpdateResponse;

import java.util.List;

/**
 * 操作文档
 *
 * @author laopan
 * @date 2021/4/15 0015 23:04
 */
public abstract class AbstractDocHandler<T> extends AbstractIndexInfo {
    private DocOperation esDocOperation;

    public AbstractDocHandler(DocOperation esDocOperation) {
        this.esDocOperation = esDocOperation;

    }

    public DocOperation getEsDocOperation() {
        return esDocOperation;
    }

    public void setEsDocOperation(DocOperation esDocOperation) {
        this.esDocOperation = esDocOperation;
    }

    /**
     * 删除文档
     *
     * @param id
     */
    public boolean deleteDoc(String id) {
        return esDocOperation.deleteDocById(getIndex(), id);
    }

    /**
     * 是否存在数据
     *
     * @param id
     * @return
     */
    public boolean existData(String id) {
        return esDocOperation.exists(getIndex(), id);
    }

    public boolean saveDoc(T entity) {
        String json = JsonUtils.toJson(entity);
        String idData = JsonUtils.getFiledData(entity, getIdFieldName());
        return saveDoc(json, idData);
    }

    public boolean saveBatchDoc(List<T> entity) {
        JsonArray jsonArray = JsonUtils.toJsonArray(entity, getEntityClass());
        BulkResponse resp = esDocOperation.saveBatchDoc(getIndex(), jsonArray, getIdFieldName());
        return null != resp && resp.hasFailures();
    }

    public boolean saveDoc(String json, String idData) {
        return esDocOperation.saveDoc(getIndex(), json, idData);
    }

    public boolean updateField(UpdateFieldInfo fieldInfo) {
        UpdateResponse response = esDocOperation.updateField(getIndex(), fieldInfo);
        return null != response;
    }

    public boolean updateArrayField(UpdateFieldArray fieldArray) {
        UpdateResponse response = esDocOperation.updateArrayField(getIndex(), fieldArray);
        return null != response;
    }

    /**
     * 获取实体对象
     *
     * @return
     */
    protected abstract Class<T> getEntityClass();

    /**
     * id字段名称,根据实体定义的不同，重写该方法，否则默认都是id
     *
     * @return
     */
    protected String getIdFieldName() {
        return "id";
    }
}
